package info.cs52.fes.action.dish;

import info.cs52.fes.Application;
import info.cs52.fes.FesAction;
import info.cs52.fes.dao.RecipeDAO;
import info.cs52.fes.data.Recipe;

import java.io.IOException;
import java.util.Date;

import javax.persistence.PersistenceException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

public class AddAction extends FesAction {

	public AddAction() {
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			if (!"add".equals(req.getParameter("submit")) || !validate(req)) {
				return;
			}
			Recipe recipe = new Recipe();
			recipe.setId(req.getParameter("id"));
			recipe.setName(req.getParameter("name"));
			recipe.setDescription(req.getParameter("desc"));
			recipe.setImage(req.getParameter("image"));
			recipe.setLastModified(new Date());
			RecipeDAO.persist(recipe);
			resp.sendRedirect(Application.getPath() + "/dish/view?id=" + recipe.getId());
		} catch (PersistenceException e) {
			e.printStackTrace();
		}
	}
	
	private boolean validate(HttpServletRequest req) {
		String id = req.getParameter("id");
		if (StringUtils.isEmpty(id)) {
			message = "Thiếu ID món ăn";
			return false;
		}
		String name = req.getParameter("name");
		if (StringUtils.isEmpty(name)) {
			message = "Thiếu tên món ăn";
			return false;
		}
		if (StringUtils.isEmpty(req.getParameter("desc"))) {
			message = "Thiếu mô tả món ăn";
			return false;
		}		
		if (RecipeDAO.find(id) != null) {
			message = "ID đã tồn tại";
			return false;
		}
		if (RecipeDAO.findByName(name) != null) {
			message = "Tên đã tồn tại";
			return false;
		}
		return true;
	}
	
}
